import { PageContainer } from '@ant-design/pro-components';
import { Card, Row, Col, Typography, Input, Pagination, Empty } from 'antd';
import { ApiOutlined, MobileOutlined, GlobalOutlined, IdcardOutlined, SafetyCertificateOutlined, ScanOutlined, QrcodeOutlined, FileSearchOutlined, SearchOutlined } from '@ant-design/icons';
import React, {useState, useMemo, useEffect} from 'react';
import {queryOpenApiById, queryOpenApiForGet} from "@/api/openapi/openapi";
import ApiDrawer from './components/ApiDrawer';

const { Title } = Typography;

interface ApiCardProps {
  icon: React.ReactNode;
  name: string;
  description: string;
  status: string;
}

const ApiCard: React.FC<OpenApiEntity & { onClick: () => void }> = ({ icon, name, description, status, onClick }) => (
  <Card
    hoverable
    style={{ height: '100%' }}
    bodyStyle={{ height: '100%', display: 'flex', flexDirection: 'column' }}
    onClick={onClick}
  >
    <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          width: 48,
          height: 48,
          borderRadius: '50%',
          backgroundColor: '#f0f5ff',
          marginRight: 16,
        }}
      >
        <FileSearchOutlined style={{ fontSize: 24, color: '#1677ff' }} />
      </div>
      <div style={{ flex: 1 }}>
        <Title level={5} style={{ margin: 0 }}>
          {name}
        </Title>
        <span style={{ fontSize: 12, color: '#00b578' }}>可用额度：50次/天</span>
      </div>
    </div>
    <div style={{ flex: 1, color: '#697b8c', fontSize: 14 }}>{description}</div>
  </Card>
);

const OpenApiIndex: React.FC = () => {
  const [searchText, setSearchText] = useState<string>('');
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [selectedApi, setSelectedApi] = useState<any>(null);
  const pageSize = 8; // 每页显示的API数量

  const apiList: ApiCardProps[] = [
    {
      icon: <MobileOutlined style={{ fontSize: 24, color: '#1677ff' }} />,
      name: '手机号码归属地查询',
      description: '支持全国手机号码归属地查询，返回手机号码所属运营商、归属地等信息',
      status: '可用额度：50次/天',
    },
    {
      icon: <GlobalOutlined style={{ fontSize: 24, color: '#1677ff' }} />,
      name: 'IP地址归属地查询',
      description: '支持IPv4/IPv6地址归属地查询，返回IP地址所属地区、运营商等信息',
      status: '可用额度：50次/天',
    },
    {
      icon: <IdcardOutlined style={{ fontSize: 24, color: '#1677ff' }} />,
      name: '身份证号码归属地查询',
      description: '支持中国大陆居民身份证归属地查询，返回身份证所属地区等信息',
      status: '可用额度：50次/天',
    },
    {
      icon: <SafetyCertificateOutlined style={{ fontSize: 24, color: '#1677ff' }} />,
      name: '垃圾分类识别查询',
      description: '支持垃圾分类查询，帮助用户准确进行垃圾分类',
      status: '可用额度：50次/天',
    },
    {
      icon: <ScanOutlined style={{ fontSize: 24, color: '#1677ff' }} />,
      name: '二维码生成',
      description: '支持自定义内容生成二维码，可设置大小、颜色等参数',
      status: '可用额度：50次/天',
    },
    {
      icon: <QrcodeOutlined style={{ fontSize: 24, color: '#1677ff' }} />,
      name: '图片OCR识别',
      description: '支持图片文字识别，可识别多种语言的文字内容',
      status: '可用额度：50次/天',
    },
    {
      icon: <FileSearchOutlined style={{ fontSize: 24, color: '#1677ff' }} />,
      name: '星座运势',
      description: '支持查询12星座每日/每周/每月/每年运势',
      status: '可用额度：50次/天',
    },
  ];

  const [currentApis,setCurrentApis] = useState<OpenApiEntity[]>([])

  // 处理页码变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    // 回到页面顶部
    window.scrollTo(0, 0);
  };

  // 处理API卡片点击
  const handleApiClick = (api: any) => {
    queryOpenApiById(api?.id).then(res => {
      setSelectedApi(res?.result);
    })
    setDrawerVisible(true);
  };

  // 关闭抽屉
  const handleCloseDrawer = () => {
    setDrawerVisible(false);
  };

  const fetchOpenApiForGet = (name: string) => {
    queryOpenApiForGet(name).then(res => {
      setCurrentApis(res?.result?.data || [])
    })
  }

  useEffect(() => {
    fetchOpenApiForGet("")
  },[])

  return (
    <PageContainer title={false}>
      <div style={{ background: '#f0f2f5', padding: 24, minHeight: '100vh' }}>
        {/* 搜索框 */}
        <div
          style={{
            marginBottom: 36,
            display: 'flex',
            justifyContent: 'center',
            position: 'relative'
          }}
        >
          <div
            style={{
              position: 'relative',
              width: '400px',
              transition: 'all 0.3s ease',
            }}
          >
            <Input
              placeholder="✨ 搜索神奇的API ✨"
              prefix={<SearchOutlined style={{ fontSize: '18px', color: '#1677ff' }} />}
              value={searchText}
              onChange={(e) => {
                setSearchText(e.target.value);
                setCurrentPage(1); // 搜索时重置为第一页
                fetchOpenApiForGet(e.target.value)
              }}
              style={{
                width: '100%',
                height: '48px',
                padding: '8px 16px',
                fontSize: '16px',
                borderRadius: '24px',
                boxShadow: '0 6px 16px rgba(0, 0, 0, 0.08)',
                border: '2px solid transparent',
                background: 'linear-gradient(white, white) padding-box, linear-gradient(45deg, #1677ff, #69c0ff) border-box',
                transition: 'all 0.3s ease',
              }}
              allowClear
            />
            <div
              style={{
                position: 'absolute',
                bottom: '-24px',
                left: '50%',
                transform: 'translateX(-50%)',
                fontSize: '12px',
                color: '#1677ff',
                fontWeight: 'bold',
                opacity: searchText ? 0 : 0.8,
                transition: 'opacity 0.3s ease',
              }}
            >
              🔍 探索更多精彩API
            </div>
          </div>
        </div>

        {/* API卡片列表 */}
        {currentApis.length > 0 ? (
          <Row gutter={[24, 24]}>
            {currentApis.map((api, index) => (
              <Col xs={24} sm={12} md={8} lg={6} key={index}>
                <ApiCard {...api} onClick={() => handleApiClick(api)} />
              </Col>
            ))}
          </Row>
        ) : (
          <Empty description="没有找到匹配的API" />
        )}

        {/* 分页控件 */}
        {currentApis.length > 0 && (
          <div style={{ marginTop: 24, textAlign: 'center' }}>
            <Pagination
              current={currentPage}
              total={currentApis.length}
              pageSize={pageSize}
              onChange={handlePageChange}
              showSizeChanger={false}
              showQuickJumper
            />
          </div>
        )}
      </div>

      {/* API详情抽屉 */}
      <ApiDrawer
        visible={drawerVisible}
        onClose={handleCloseDrawer}
        api={selectedApi}
      />
    </PageContainer>
  );
};

export default OpenApiIndex;
